//
//  WTComposePictureView.swift
//  WTSinaWeibo
//
//  Created by  Wellim on 16/7/3.
//  Copyright © 2016年  Wellim. All rights reserved.
//

import UIKit
// cell 可重用标识符
private let pictureViewCellId = "pictureViewCell"
class WTComposePictureView: UICollectionView {

     // 告知外界弹出相册
    var composePictureViewClosure:(()->())?
    
    // 保存image的数组
    var imageList: [UIImage] = [UIImage]()
    
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
     // MARK: - 供外界调用的方法
    func addImages(image: UIImage){
        
        imageList.insert(image, atIndex: 0)
         // 如果count 大于9 删除最后一张图片
        if imageList.count > 9 {
            imageList.removeLast()
         
        }
        
        // 如果imageList.count > 0  显示配图
        hidden = false
        
        
         // 记得刷新数据
         reloadData()
    }
    
   
    // MARK: - 设置视图
   
    private func setUpUI(){
      
        // 首次进入想把当前配图隐藏
        hidden = true
      backgroundColor = UIColor.whiteColor()
      
      dataSource = self
      delegate = self
      // 注册cell
      registerClass(WTComposePictureViewCell.self, forCellWithReuseIdentifier: pictureViewCellId)
       // 设置layout
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        
        let itemMargin:CGFloat = 5
        
        let cellWh = (kScreenWidth - 20 - itemMargin * 2)/3
        // 设置item
        flowLayout.itemSize = CGSize(width: cellWh, height: cellWh)
        
        // 设置垂直和水平间距
        flowLayout.minimumInteritemSpacing = itemMargin
        flowLayout.minimumLineSpacing = itemMargin
        
        
        
    }
    
    /*
     如果有四张图片 显示 5个cell  最后一个加号图片
     如果有0张图片或者9张图片 没有加号按钮  显示9个cell
     */

    
    
}

extension WTComposePictureView:UICollectionViewDataSource,UICollectionViewDelegate{

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let count = imageList.count
        if count == 0 || count == 9 {
            return count
        
        }else{
            return imageList.count + 1
        
        }
        
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureViewCellId, forIndexPath: indexPath) as! WTComposePictureViewCell
        
//        cell.backgroundColor = RandomColor()
        // 给cell设置加号
        if imageList.count == indexPath.item {
            
            cell.image = nil
        }else{
        
          cell.image = imageList[indexPath.item]
        }
        
        //实现闭包
        cell.deleteBtnClosure = {
        // 删除数组指定元素
         self.imageList.removeAtIndex(indexPath.item)
          
            // 如果count = 0 隐藏配图
            if self.imageList.count == 0 {
                
                self.hidden = true
            }
    
         //刷新UI
          self.reloadData()
            
        
        }
        
        
        return cell
        
    }

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
         // 如果数组的count ==  indexPath.item 就是加号按钮
        if imageList.count == indexPath.row {
//            print("加号按钮")
          composePictureViewClosure?()
            
        }
    }

}


// 自定义cell

class WTComposePictureViewCell: UICollectionViewCell {
    
    // 声明删除按钮闭包
    var deleteBtnClosure: (()->())?
    
     // 供外界给其赋值
    var image: UIImage? {
    
        didSet{
            // itemImageView.image = image
            // 要设置加号按钮
            if image == nil {
                
                itemImageView.image = UIImage(named: "compose_pic_add")
                itemImageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                //隐身删除按钮
                deleteBtn.hidden = true
                
            }else {
            
               // 正常显示
                itemImageView.image = image
                
                // 解决cell重用问题

                itemImageView.highlightedImage = nil
                 //显示删除按钮
                deleteBtn.hidden = false
            
            }
         }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 设置视图
    private func setUpUI(){
    
        backgroundColor = UIColor.whiteColor()
       
        // 添加控件
        contentView.addSubview(itemImageView)
        contentView.addSubview(deleteBtn)
        
        // 添加约束
       itemImageView.snp_makeConstraints { (make) in
        
        make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        
        
        }
    
       deleteBtn.snp_makeConstraints { (make) in
        
        make.top.equalTo(contentView)
        make.right.equalTo(contentView)
        
        }
        
     
    }
    
    // MARK: -  懒加载控件
    private lazy var itemImageView:UIImageView = UIImageView()
    
    // 删除按钮
    private lazy var deleteBtn:UIButton = {
    
     let button = UIButton()
     
      button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
      // 添加点击事件
      button.addTarget(self, action: "deleteBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
    
       return button
    }()
    
    @objc private func deleteBtnClick(){
    
//     print("haha")
     
      //执行闭包
      deleteBtnClosure?()
        
    }
    
}




